package com.xmqian.app.project.ui.common.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.coszero.uilibrary.dialog.AlertDialog;
import com.coszero.utilslibrary.phone.PhoneNetStateUtils;
import com.coszero.utilslibrary.utils.LogX;
import com.coszero.utilslibrary.utils.ToastUtils;
import com.xmqian.app.R;
import com.xmqian.app.common.base.mvp.BaseMvpFragment;
import com.xmqian.app.project.ui.common.contract.MyWebViewContract;
import com.xmqian.app.project.ui.common.model.MyWebViewModel;
import com.xmqian.app.project.ui.common.presenter.MyWebViewPresenter;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;

/**
 * Desc： 展示网页界面
 * <p>
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/9/12 17:50
 */
public class MyWebViewFragment extends BaseMvpFragment<MyWebViewContract.View, MyWebViewPresenter> implements MyWebViewContract.View {

    //因接口地址不同，特殊处理
    public static final int HELP_FEEDBACK = 0x56;

    private static final String EXTRA_TYPE = "mCurrentType";
    private static final String EXTRA_PAGE_ID = "pageId";
    private static final String EXTRA_TEXT = "text";
    private static final String EXTRA_TITLE = "title";

    //认证相关type，需要检测服务器返回的 json 字符串
    public static final int TYPE_BANK_CERT = 0x11;
    public static final int TYPE_MOBILE_CERT = 0x22;

    //银行支付type，需要检测服务器返回的 json 字符串
    public static final int TYPE_BANK_PAYMENT = 0x33;

    public static final int TYPE_SINGLE_PAGE = 0x44;

    //当前打开的type类型，-1 为默认类型，表示仅打开url/文本
    private int mCurrentType = -1;

    @BindView(R.id.pwv_web)
    WebView mWebView;

    String mUrl;
    String mTitle;

    private int pageId;
    private TitleCallBack mTitleCallBack;

    /**
     * @param type 类型
     * @param pageId 网页请求id
     * @param title 标题
     * @param text 内容，有可能是链接地址，有可能是网页内容
     * @return
     */
    public static MyWebViewFragment newInstance(int type, int pageId, String title, String text) {
        Bundle args = new Bundle();
        args.putInt(EXTRA_TYPE, type);
        args.putInt(EXTRA_PAGE_ID, pageId);
        args.putString(EXTRA_TITLE, title);
        args.putString(EXTRA_TEXT, text);
        MyWebViewFragment fragment = new MyWebViewFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof TitleCallBack) {
            mTitleCallBack = (TitleCallBack) context;
        } else {
            new Throwable("no implement TitleCallBack");
        }
    }

    @Override
    protected void lazyLoadData() {

    }

    @Override
    public int getLayoutResource() {
        return R.layout.fragment_my_web_view;
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    @Override
    protected void initView() {
        //获取intent里的值并设置标题
        Bundle data = getArguments();
        mUrl = data.getString(EXTRA_TEXT);
        mTitle = data.getString(EXTRA_TITLE);
        mCurrentType = data.getInt(EXTRA_TYPE, -1);
        mTitleCallBack.setTitleListenner(mTitle);

        //WebView 配置相关
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        mWebView.getSettings().setLoadsImagesAutomatically(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        if (PhoneNetStateUtils.isNetWorkAvailble(getActivity())) {
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        } else {
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.getSettings().setAllowContentAccess(true);
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setSavePassword(false);
        mWebView.getSettings().setSaveFormData(false);

        mWebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            // 监听下载功能，当用户点击下载链接的时候，直接调用系统的浏览器来下载
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        });

        mWebView.setWebViewClient(new MyWebViewClient());
        //自定义控件已设置
//        mWebView.setWebChromeClient(new WebChromeClient());

        if (mCurrentType == TYPE_SINGLE_PAGE) {
            pageId = getArguments().getInt(EXTRA_PAGE_ID, 0);
            getPresenter().getSinglePage(pageId);
            return;
        }

        //特殊
        if (mCurrentType == HELP_FEEDBACK) {
            pageId = getArguments().getInt(EXTRA_PAGE_ID, 0);
            getPresenter().getFeedBackInfo(pageId);
            return;
        }

        //如果以http为起始，说明是url地址，否则作为文本打开内容
        if (mUrl.startsWith("http")) {
            mWebView.getSettings().setUseWideViewPort(true);
            mWebView.getSettings().setLoadWithOverviewMode(true);
            mWebView.loadUrl(mUrl);
        } else {
            loadHtmlContent(mUrl);
        }
    }

    private void loadHtmlContent(String content) {
        mWebView.loadDataWithBaseURL(null, getHtmlData(content), "text/html;charset=UTF-8", null, null);
    }

    private String getHtmlData(String bodyHTML) {
        String head = "<head><style>img{max-width: 100%; width:auto; height: auto;}</style></head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body><html>";
    }

    @Override
    protected void initData() {

    }

    @Override
    protected MyWebViewPresenter createPresenter() {
        return new MyWebViewPresenter();
    }

    @Override
    public void showLoadingView() {

    }

    @Override
    public void hideLoadingView() {

    }

    @Override
    public void onNetworkError() {

    }

    @Override
    public void onGetSinglePageSucceed(MyWebViewModel pageBean) {
        setTitle(pageBean.getTitle());
        loadHtmlContent(pageBean.getContents());
    }

    @Override
    public void onRequestFailed(String message) {
        ToastUtils.showMsg(message);
    }

    /**
     * 逻辑处理
     */
    final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void getSource(String html) {
            LogX.i(html);
            try {
                html = html.substring(html.indexOf("{"), html.lastIndexOf("}") + 1);
                JSONObject result = new JSONObject(html);

                if (result.optInt("result") == 1) {
                    //如果是银行卡还款/支付结果成功了，跳转到订单状态页面
                    if (mCurrentType == TYPE_BANK_PAYMENT) {
//                        startActivity(new Intent(MyWebViewFragment.this, OrderSucceedActivity.class));
//                        MyWebViewFragment.this.finish();
                        return;
                    }
                }
                showResult(result.optString("message"));

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void showResult(String message) {
        AlertDialog dialog = new AlertDialog(getActivity());
        dialog.builder().setTitle("提示").setMsg(message);

        dialog.setCancelable(false);
        dialog.show();
    }


    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogX.e(url);
            if (url.contains("BackSuccess?type=1")) {
//                mPresenter.mobilezr2();
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mCurrentType == -1) return;
            if (mCurrentType == TYPE_BANK_CERT || mCurrentType == TYPE_MOBILE_CERT || mCurrentType == TYPE_BANK_PAYMENT) {
                view.loadUrl("javascript:window.java_obj.getSource(document.getElementsByTagName('body')[0].innerHTML);");
            }
        }
    }

    /**
     * 网页返回
     */
    public boolean onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return false;
    }

    public interface TitleCallBack {
        void setTitleListenner(String title);
    }
}
